import base from '@src/store/base'
import {
  getCategoryDetail,
  getInviteAwards,
  getInviteCount,
  getPromotionCode,
  inviteMember,
  registerPromoter
} from '@src/api/member';
import {storeBindingsBehavior} from 'mobx-miniprogram-bindings'
import router from "@src/router";
import member from "@src/store/member";
import {
  parseOpenCardGift,
} from "@src/common/memberCardUtils";

const COUPONTYPE = {
  cash: '代金券', 
  discount: '折扣券',
  exchange: '兑换券',
  cash_wx_busi: '微信商家代金券',
  discount_wx_busi: '微信商家折扣券',
  cash_wx_pay: '微信支付代金券',
  gift: '礼品卡',
  times: '次卡'
}
Component({
  behaviors: [storeBindingsBehavior, router.routerBehavior],
  storeBindings: [{
    store: base,
    fields: ['themeColor', 'themeTitleColor']
  }, {
    store: member,
    fields: ['isMember', 'categoryName']
  }],
  data: {
    defaultHeight: 849,
    countsData: 0,
    ruleArr: [],
    fullShareImg: null,
    shareTitle: '邀请你注册成为会员',
    SimpleShareImg: null,
    postModal: false,
  },
  methods: {
    onLogin() {
      this.fetchData();
    },
    //分享至好友
    onShareAppMessage(e) {
      if(e.target.id==="toFriend"){
        //用于后台生成推广记录
        this.selectComponent("#share-dialog").close();
        this.handleInviteSuccess();
        return {
          title: this.data.shareTitle,
          path: `pages/index/main?scene=${this.data.scene}&receiveWay=2`,
          desc: "",
          imageUrl: this.data.simpleShareImg
        };
      }else {

      }
    },

    fetchData() {
      getInviteAwards().then(res => {
        if (res.code === 0) {
          let respData = res.data;
          respData.memberConfigVos && respData.memberConfigVos.forEach(i => {
            switch(i.bonusType) {
              case 1:
                i.title = '注册奖励'
                i.limitDesc = '每注册成功一人，将获得以下奖励：'
                break;
              case 2:
                i.title = '充值奖励'
                i.limitDesc = i.limitAmount ? `好友每次充值金额超过${i.limitAmount}元，将获得以下奖励：` : '好友每次充值，将获得以下奖励：'
                break;
              case 3:
                i.title = '消费奖励'
                i.limitDesc = i.limitAmount ? `好友每次消费订单金额超过${i.limitAmount}元（不含配送费），将获得以下奖励：` : '好友每次消费，将获得以下奖励： '
                break;
              default:
                i.title = ''
                break;
            }
            if(i.bonusCouponVos && i.bonusCouponVos.length) {
              i.bonusCouponVos.forEach(coupon => {
                const type = COUPONTYPE[coupon.couponType.toLowerCase()]
                coupon.name = `【${type}】${coupon.couponName} ${coupon.amount}张`
              })
            }
          })
          this.setData({
            ruleArr: respData.memberConfigVos
          })
          // this.parseAwards(respData);
        }
      })
      getPromotionCode().then(res => {
        if (res.code === 0) {
          //请求成功
          if (res.data) {
            this.setData({scene: res.data})
          } else {
            //弹出modal获取手机号
            this.showGetPhoneDialog();
          }
        }
      })
      if (this.data.isMember) {
        getCategoryDetail().then(res => {
          let openCardCouponAward = res.data.openCardCouponAward;
          let category = res.data.category;
          let openCardGift = parseOpenCardGift(category, openCardCouponAward);
          let shareTitle = "";
          openCardGift.forEach(value => {
            shareTitle += `送${value.title}${value.value}${value.aFix},`;
          });
          shareTitle = shareTitle.substring(0, shareTitle.length - 1);
          shareTitle = `邀请你注册成为${category.categoryName}会员,` + shareTitle;
          this.setData({shareTitle})
        })
      }
      this.fetchInviteCount();
    },
    showGetPhoneDialog() {
      this.selectComponent("#get-phone").open({text: "使用邀请功能,我们需要验证您的手机号", auto: false}).then(data => {
        registerPromoter(data).then(res => {
          if (res.code === 0) {
            if (res.data) {
              this.scene = res.data;
              this.setData({scene: res.data})
              this.fetchData();
            } else {
              this.showGetPhoneDialog();
            }
          } else {
            this.showGetPhoneDialog();
          }
        })
      }).catch(() => {
        router.back();
      })
    },
    fetchInviteCount(e) {
      if(e){
        this.setData({countsData: e.detail.data});
        return
      }
      getInviteCount().then(res => {
        this.setData({countsData: res.data})
      })
    },
    parseAwards(respData) {
      ruleArr = memberConfigVos
      let couponBonusArr = [];
      // if (respData.couponBonus) {
      //   couponBonusArr = JSON.parse(respData.couponBonus);
       
      //   console.log(couponBonusArr)
      // }
      //会员规则字段拼接
      let ruleArr = [];
      if (enableMemberBonus && memberConfigVos.length) {
        
        // if (respData.balanceBonus) {
        //   ruleArr.push(`每成功注册一个人，你都将获得${respData.balanceBonus / 100}元返现，将会自动返现到你的钱包账户中`);
        // }
        // if (respData.pointsBonus) {
        //   ruleArr.push(`每成功注册一个人，你都将获得${respData.pointsBonus}个积分，积分会自动赠送到你的积分账户`);
        // }
        // if (couponBonusArr.length) {
        //   let couponCopyString = "";
        //   couponBonusArr.forEach(value => {
        //     couponCopyString += `【${value.couponName}】${value.amount}张，`;
        //   });
        //   ruleArr.push(`每成功注册一个人，你都将获得优惠券${couponCopyString.substring(0, couponCopyString.length - 1)}`);
        // }
      } else {
        ruleArr.push({
          title: '分享会员规则',
          content: '分享链接或者二维码给好友，好友即可注册成为会员'
        });
      }
      this.setData({ruleArr: ruleArr})
    },
    handleInviteSuccess() {
      inviteMember().then(res => {
        if (res.code === 0) {
          this.fetchInviteCount();
        }
      });
    },
    handleFullPoster(e) {
      this.setData({fullShareImg: e.detail.shareImg})
      console.log('分享会员奖励 - 海报 fullShareImg--',this.data.fullShareImg)
    },
    handleSimplePoster(e) {
      this.setData({simpleShareImg: e.detail.shareImg})
      console.log('分享会员奖励 - 转发好友 simpleShareImg--',this.data.simpleShareImg)
    },

    handleToShare() {
      this.selectComponent("#share-dialog").open();
    },
    handleClosePost() {
      this.setData({postModal: false})
    },
    handleSavePost() {
      wx.saveImageToPhotosAlbum({
        filePath: this.data.fullShareImg,
        success: (res) => {
          wx.showToast({title: `海报已保存到系统相册`, icon: "none", duration: 3000});
          this.handleInviteSuccess();
          this.handleClosePost();
        },
        fail: err => {
          if (err.errMsg === "saveImageToPhotosAlbum:fail:auth denied"
              || err.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
            // 这边微信做过调整，必须要在按钮中触发，因此需要在弹框回调中进行调用
            wx.showModal({
              title: "提示",
              content: "需要您授权保存相册",
              showCancel: false,
              success: () => {
                wx.openSetting({
                  success(settingdata) {
                    console.log("settingdata", settingdata);
                    if (settingdata.authSetting["scope.writePhotosAlbum"]) {
                      wx.showModal({title: "提示", content: "获取权限成功,再次点击保存图片到相册", showCancel: false});
                    } else {
                      wx.showModal({title: "提示", content: "获取保存到相册权限失败，将无法保存到相册", showCancel: false});
                    }
                  }
                });
              }
            });
          }
        }
      });
    },
    handleShowMomentsPost() {
      this.setData({postModal: true})
    }
  },
})
